package com.xpgk.mvc.collection.binShopService;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.xpgk.annotation.Service;
import com.xpgk.constant.ConstantRender;
import com.xpgk.mvc.base.BaseService;
import com.xpgk.mvc.bentryRegister.Customer;
import com.xpgk.mvc.bentryRegister.CustomerDetail;
import com.xpgk.mvc.bentryRegister.CustomerHabit;
import com.xpgk.mvc.bentryRegister.CustomerProduct;
import com.xpgk.mvc.bentryRegister.CustomerProductSurplus;
import com.xpgk.mvc.binShopService.CustomerService;
import com.xpgk.mvc.binShopService.CustomerServiceMonthNurse;
import com.xpgk.mvc.binShopService.CustomerServiceNurse;
import com.xpgk.mvc.binShopService.ServicePartSize;
import com.xpgk.mvc.binShopService.ServiceShaping;
import com.xpgk.mvc.bloseWeight.DelWeiTarget;
import com.xpgk.mvc.bloseWeight.DelWeiTargetSum;
import com.xpgk.mvc.codeSet.Code;
import com.xpgk.mvc.measurement.Temporary;
import com.xpgk.mvc.productOutin.ProductOutin;
import com.xpgk.mvc.productSet.Product;
import com.xpgk.mvc.productSet.ProductExperience;
import com.xpgk.mvc.productStock.ProductStock;
import com.xpgk.mvc.productStock.ProductStockInfo;
import com.xpgk.mvc.statistic.dailyTotalStatistic.DailyNursingTotal;
import com.xpgk.mvc.statistic.monthTotalStatistic.MonthTotal;
import com.xpgk.mvc.statistic.yearTotalStatistic.YearTotal;
import com.xpgk.mvc.user.User;
import com.xpgk.tools.ToolDateTime;
import com.xpgk.tools.ToolRandoms;

@Service(name = BinShopColServiceService2.serviceName)
public class BinShopColServiceService2 extends BaseService {
	@SuppressWarnings("unused")
	private static final Log log = Log.getLog(BinShopColServiceService2.class);
	public static final String serviceName = "binShopColServiceService2";
	
	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟 
	
	/**塑形，获取服务部信息
	 * 
	 * @param customerIds
	 * @param curUserIds
	 * @return
	 */
	public List<Map> getPartInfo(String customerIds, String curUserIds) {
		List<Map> partInfoList = new ArrayList<>();
		// 获取服务部位
		List<Code> codeList = Code.cacheGetChild(Code.fwbw_ids);
		if (codeList != null && codeList.size() > 0) {
			for (int i = 0; i < codeList.size(); i++) {
				Map<String, String> map = new HashMap<>();
				map.put("positionIds", codeList.get(i).getStr(Code.column_ids));
				map.put("position", codeList.get(i).getStr(Code.column_name));
				map.put("userids", curUserIds);
				map.put("name", User.cacheGetByUserId(curUserIds).getStr(User.column_name));
				String cusprosql = getSqlMy(CustomerProduct.sqlId_selByCusAndUseIdsAndPartIds);
				List<CustomerProduct> cpList = CustomerProduct.dao.find(cusprosql, Code.cpytFw_ids, customerIds,
						codeList.get(i).getStr(Code.column_ids));
				if (cpList != null && cpList.size() > 0) {
					for (int j = 0; j < cpList.size(); j++) {
						map.put(cpList.get(j).getStr(Product.column_ids), cpList.get(j).getStr(Product.column_ids));
						map.put("use_" + cpList.get(j).getStr(Product.column_ids),
								cpList.get(j).getFloat(ProductExperience.column_experience).toString());
						map.put("surplus_" + cpList.get(j).getStr(Product.column_ids),
								cpList.get(j).getFloat(CustomerProduct.column_totalExperience).toString());
					}
				}
				partInfoList.add(map);
			}

		}

		return partInfoList;

	}

	/**
	 * 获取测量部位尺寸
	 * 
	 * @param customerIds
	 * @return
	 */
	public List<Map> getPartSizeInfo(String customerIds) {
		List<Map> partSizeInfoList = new ArrayList<>();
		// 获取服务部位
		List<Code> codeList = Code.cacheGetChild(Code.fwbw_ids);
		for(Code code:codeList)
		{
			List<Code> cList = Code.cacheGetChild(code.getStr(Code.column_ids));
			for(Code cc:cList){
				Map<String, String> map = new HashMap<>();
				map.put("positionIds", cc.getStr(Code.column_ids));
				map.put("position", cc.getStr(Code.column_name));
				List<ServicePartSize>  spsList=ServicePartSize.dao.getServicePartSize(customerIds,cc.getStr(Code.column_ids));
				if(spsList!=null &&  spsList.size()>0)
				{
					map.put("positionSize", spsList.get(0).getFloat(ServicePartSize.column_size).toString());
				}else
				{
					map.put("positionSize", "0");
				}
				partSizeInfoList.add(map);
			}
		}

		return partSizeInfoList;
	}

	/**
	 * 获取默认生活习惯
	 * 
	 * @param cusIds
	 * @param orgIds
	 * @return
	 */
	public CustomerHabit getCusHabit(String cusIds, String orgIds) {
		String servicesql = getSqlMy(CustomerService.sqlId_selByCusAndOrg);
		List<CustomerService> csList = CustomerService.dao.find(servicesql, cusIds, orgIds);
		if (csList != null && csList.size() > 0) {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("column", CustomerHabit.column_serviceID);
			String sql = getSqlByBeetl(CustomerHabit.sqlId_column, param);
			CustomerHabit ch = CustomerHabit.dao.findFirst(sql, csList.get(0).getStr(CustomerService.column_ids));
			if (ch != null) {
				return ch;
			} else {
				return null;
			}

		} else {
			return null;
		}
	}

	/**
	 * 保存服务和生活习惯
	 * 
	 */
	public String saveInfo(Customer c, CustomerHabit ch, CustomerService cs, String orgIds, String userIds,
			List<ServicePartSize> spsList, List<ServiceShaping> ssList, List<CustomerProduct> cpList,
			String plaster_ids) {
		String msg = ConstantRender.render_success_code; 
		
		CustomerDetail cd = c.getCustomerDetail();
		SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
		String gxsj = "%" + dateFormater.format(new Date()) + "%";
		// 保存服务记录
		cs.set(CustomerService.column_organids, orgIds)
				.set(CustomerService.column_customerID, c.getStr(Customer.column_ids))
				.set(CustomerService.column_userID, userIds)
				.set(CustomerService.column_lastWeight, cd.getFloat(CustomerDetail.column_nowWeight))
				.set(CustomerService.column_createDate, new Date());
		if (!cs.save()) {
			log.debug("保存服务记录失败");
			throw new RuntimeException("保存服务记录失败!");
		}
		if (cs.getStr(CustomerService.column_isPlaster).equals("1")) {
			String plaster[] = plaster_ids.split(",");
			for (int i = 0; i < plaster.length; i++) {
				if (plaster[i] != null && !plaster[i].equals("")) {
					Product p = Product.dao.findById(plaster[i]);
					String pstSql = getSqlMy(ProductStock.sqlId_selPSByOidsAndPids);
					ProductStock pst = ProductStock.dao.findFirst(pstSql, orgIds, p.getStr(Product.column_ids));
					if (pst != null && pst.getFloat(ProductStock.column_num) >= 1) 
					{
						//保存药贴出库记录
						ProductOutin  po = new  ProductOutin();
						po.set(ProductOutin.column_ids, ToolRandoms.getUuid(true))
							.set(ProductOutin.column_organIds, orgIds)
							.set(ProductOutin.column_typeIds, p.getStr(Product.column_typeIds))
							.set(ProductOutin.column_productIds, p.getStr(Product.column_ids))
							.set(ProductOutin.column_number, 1)
							.set(ProductOutin.column_price, 0)
							.set(ProductOutin.column_date, new Date())
							.set(ProductOutin.column_style, "1")
							.set(ProductOutin.column_userIds, userIds)
							.set(ProductOutin.column_gxsj, new Date());
						if(!po.save())
						{
							log.debug("保存"+p.getStr(Product.column_name) +"出库记录失败！！");
							throw new RuntimeException("保存"+p.getStr(Product.column_name) + "出库记录失败！！");
						}
						// 更新产品库存
						
						// 根据日期和机构id,产品id查出当日是否有库存记录
						String pstInsql = getSqlMy(ProductStockInfo.sqlId_selByOidsAndPidsAndTime);
						ProductStockInfo psi = ProductStockInfo.dao.findFirst(pstInsql, orgIds,
								p.getStr(Product.column_ids), gxsj);
					
							float num1 = pst.getFloat(ProductStock.column_num) - 1;
							pst.set(ProductStock.column_num, num1).set(ProductStock.column_gxsj, new Date());
							if (!pst.update()) {
								log.debug("更新产品总库存失败");
								throw new RuntimeException("更新产品总库存失败!");
							}
							if (psi != null) {
								// 库存详细信息减少库存
								float num = psi.getFloat(ProductStockInfo.column_stock) - 1;
								psi.set(ProductStockInfo.column_stock, num)
										.set(ProductStockInfo.column_gxsj, new Date()).update();

							} else {
								ProductStockInfo psInfo = new ProductStockInfo();
								String psinfoids = ToolRandoms.getUuid(true);
								psInfo.set(ProductStockInfo.column_ids, psinfoids)
										.set(ProductStockInfo.column_organids, orgIds)
										.set(ProductStockInfo.column_productID, p.getStr(Product.column_ids))
										.set(ProductStockInfo.column_type, p.getStr(Product.column_typeIds))
										.set(ProductStockInfo.column_stock, pst.getFloat(ProductStock.column_num))
										.set(ProductStockInfo.column_gxsj, new Date());
								if (!psInfo.save()) {
									log.debug("保存产品库存记录失败！！");
									throw new RuntimeException("保存产品库存记录失败!");
								}
							}
						} else {
							log.debug(p.getStr(Product.column_name) + "库存不够，无法购买！！");
//							throw new RuntimeException(p.getStr(Product.column_name) + "库存不够，请先入库！！");
							msg=p.getStr(Product.column_name) + "库存不够，请先入库！！";
						}
				}
			}
		}
		//如果顾客为单疗程顾客，到店服务一次减少一次单疗程次数
		String  lcsql=getSqlMy(CustomerProduct.sqlId_selByCusAndType);
		CustomerProduct  lccp = CustomerProduct.dao.findFirst(lcsql,c.getStr(Customer.column_ids),Code.lc_ids,orgIds);
		if(lccp!=null && lccp.getStr("proUnits").equals(Code.dlc_units))
		{
			CustomerProduct  dlccp=CustomerProduct.dao.findById(lccp.getStr("ids"));
			dlccp.set(CustomerProduct.column_totalExperience, dlccp.getFloat(CustomerProduct.column_totalExperience)-1)
				.set(CustomerProduct.column_updateDate, new Date());
			if (!dlccp.update()) {
				log.debug("更新单疗程剩余失败");
				throw new RuntimeException("更新单疗程剩余失败!");
			}
		}
				
				
				
				
		
		// 保存塑形
		if (ssList.size() > 0) {
			for (ServiceShaping ss : ssList) {
				ss.set(ServiceShaping.column_serviceIds, cs.getStr(CustomerService.column_ids))
						.set(ServiceShaping.column_customerIds, c.getStr(Customer.column_ids))
						.set(ServiceShaping.column_time, new Date());
				if (!ss.save()) {
					log.debug("保存塑形失败");
					throw new RuntimeException("保存塑形失败!");
				}
			}
			// 更新产品剩余量
			if (cpList.size() > 0) {
				for (CustomerProduct cp : cpList) {

					String cpSql = getSqlMy(CustomerProduct.sqlId_selByCusAndPro);
					CustomerProduct cuspro = CustomerProduct.dao.findFirst(cpSql, c.getStr(Customer.column_ids),
							cp.getStr(CustomerProduct.column_productID), orgIds);
					CustomerProductSurplus  cps=CustomerProductSurplus.dao.getCustomerProductSurplus(c.getStr(Customer.column_ids), cp.getStr(CustomerProduct.column_productID), orgIds, gxsj);
					if (cuspro != null) {
						double num=Math.ceil(cp.getFloat(CustomerProduct.column_totalExperience)/cuspro.getFloat(CustomerProduct.column_proExperience));
						cuspro.set(CustomerProduct.column_capacities, cp.getFloat(CustomerProduct.column_capacities))
								.set(CustomerProduct.column_totalExperience, cp.getFloat(CustomerProduct.column_totalExperience))
						        .set(CustomerProduct.column_count, num)
								.set(CustomerProduct.column_updateDate, new Date());
						if (!cuspro.update()) {
							log.debug("更新产品剩余量失败");
							throw new RuntimeException("更新产品剩余量失败!");
						}
						if(cps!=null)
						{
							//更新顾客产品剩余详细信息
							cps.set(CustomerProductSurplus.column_totalExperience, cp.getFloat(CustomerProduct.column_totalExperience))
							.set(CustomerProductSurplus.column_count, num)
							.set(CustomerProductSurplus.column_gxsj, new Date());
							if (!cps.update()) {
								log.debug("更新顾客产品明细失败！！");
								throw new RuntimeException("更新顾客产品明细失败!");
							}
						}else
						{
							//保存顾客产品剩余详细信息
							Product  p=Product.dao.findById(cp.getStr(CustomerProduct.column_productID));
							CustomerProductSurplus  cusprosur=new CustomerProductSurplus();
							cusprosur.set(CustomerProductSurplus.column_ids, ToolRandoms.getUuid(true))
									.set(CustomerProductSurplus.column_organIds, orgIds)
									.set(CustomerProductSurplus.column_customerIds, c.getStr(Customer.column_ids))
									.set(CustomerProductSurplus.column_productIds, cp.getStr(CustomerProduct.column_productID))
									.set(CustomerProductSurplus.column_count, num)
									.set(CustomerProductSurplus.column_proExperience,  p.getStr(Product.column_proExperience))
									.set(CustomerProductSurplus.column_totalExperience, cp.getFloat(CustomerProduct.column_totalExperience))
									.set(CustomerProductSurplus.column_gxsj, new Date());
							if (!cusprosur.save()) {
								log.debug("保存顾客产品明细失败！！");
								throw new RuntimeException("保存顾客产品明细失败!");
							}
						}
					}
				}
			}
		}

		
		// 保存尺寸
		if (spsList.size() > 0) {
			for (ServicePartSize sps : spsList) {
				sps.set(ServicePartSize.column_serviceIds, cs.getStr(CustomerService.column_ids))
						.set(ServicePartSize.column_customerIds, c.getStr(Customer.column_ids))
						.set(ServicePartSize.column_createDate, new Date());
				if (!sps.save()) {
					log.debug("保存测量尺寸失败");
					throw new RuntimeException("保存测量尺寸失败!");
				}
			}
		}
		// 更新顾客详情本次体重和到店时间

		if (cd != null) {
			cd.set(CustomerDetail.column_nowWeight, cs.getFloat(CustomerService.column_weight))
					.set(CustomerDetail.column_toStoreDate, new Date());
			if (!cd.update()) {
				log.debug("更新顾客详情本次体重和到店时间失败");
				throw new RuntimeException("更新顾客详情本次体重和到店时间失败!");
			}
		}
		//保存顾客日常
		ch.set(CustomerHabit.column_serviceID, cs.getStr(CustomerService.column_ids))
			.set(CustomerHabit.column_customerID, c.getStr(Customer.column_ids))
			.set(CustomerHabit.column_organIds, orgIds)
		    .set(CustomerHabit.column_gxsj, new Date());
		if(!ch.save())
		{
			log.debug("保存顾客生活日常失败");
			throw new RuntimeException("保存顾客生活日常失败!");
		}
		
		return msg;

	}

	/**
	 * 获取减重计划
	 * 
	 * @param cusIds
	 * @return
	 */
	public Map<String,Object> getDelweight(String cusIds, String date, String orgids) {
		String msg = ConstantRender.render_success_code;
		Map<String, Object>  map=new  HashMap<>();
		List list = new ArrayList<>();
		String sql = getSqlMy(DelWeiTargetSum.sqlId_selByCusAndDate);
		List<DelWeiTargetSum> dtsList = DelWeiTargetSum.dao.find(sql, cusIds, date, date);
		if (dtsList != null && dtsList.size() > 0 && dtsList.size() < 2) {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("column", DelWeiTarget.column_targetIds);
			String dwtsql = getSqlByBeetl(DelWeiTarget.sqlId_column, param);
			List<DelWeiTarget> dwtList = DelWeiTarget.dao.find(dwtsql, dtsList.get(0).getStr(DelWeiTarget.column_ids));
			if (dwtList != null && dwtList.size() > 0) {
				for (DelWeiTarget dwt : dwtList) {
					Map mm = new HashMap<>();
					mm.put("schedules", dwt.getStr(DelWeiTarget.column_schedule));
					mm.put("starttime", dwt.getDate(DelWeiTarget.column_startTime));
					mm.put("endtime", dwt.getDate(DelWeiTarget.column_endTime));
					mm.put("planner", dwt.getInt(DelWeiTarget.column_planToStoreNum));
					String serSql = getSqlMy(CustomerService.sqlId_selByDate);
					List<CustomerService> csList = CustomerService.dao.find(serSql, cusIds, orgids,
							dwt.getDate(DelWeiTarget.column_startTime).toString(),
							dwt.getDate(DelWeiTarget.column_endTime).toString());
					mm.put("reality", csList.size());
					// 创建一个数值格式化对象
					NumberFormat numberFormat = NumberFormat.getInstance();
					// 设置精确到小数点后2位
					numberFormat.setMaximumFractionDigits(2);
					float wcbl = 0;
					float delweight = 0;
					if (csList != null && csList.size() > 0) {
						wcbl = (float) csList.size() / (float) dwt.getInt(DelWeiTarget.column_planToStoreNum);
						delweight = csList.get(0).getFloat(CustomerService.column_weight)
								- csList.get(csList.size() - 1).getFloat(CustomerService.column_weight);
					}
					String jzjs = numberFormat.format(delweight / dwt.getFloat(DelWeiTarget.column_delWeiTarget) * 100);
					mm.put("analogy", numberFormat.format(wcbl * 100) + "%");
					mm.put("effect", jzjs + "%");
					list.add(mm);
				}
			}
		}
		if (dtsList.size() > 1) {
			msg = "一个顾客在同时期只能有一个总排期，请检查该顾客减重目标管理排期设置！";
		}
		map.put("msg", msg);
		map.put("delWeightList", list);
		return map;
	}

	/**
	 * 获取减重计划
	 * 
	 * @param cusIds
	 * @return
	 * @throws ParseException
	 */
	public List<CustomerService> getDelweiRecord(String orgids, String cusIds, String date) throws ParseException {
		String d="%"+date+"%";
		String sql = getSqlMy(CustomerService.sqlId_selByMonth);
		List<CustomerService> cs = CustomerService.dao.find(sql, cusIds, orgids, d);
		return cs;
	}

	public List<Record> getView(String cUserOrganIds,String name ,String phone ,String hybh) {
		 Map<String, Object> queryParam = new HashMap<String, Object>();
		 queryParam.put("organids", cUserOrganIds);
		 queryParam.put("name", name);
		 queryParam.put("phone", phone);
		 queryParam.put("hybh", hybh);
		 List<Record> lis = find(CustomerService.sqlId_selSerByOrganids, queryParam);
		return lis;
	}

	public List<Record> getTodayView(String cUserOrganIds, String name, String phone, String hybh) {
		 Map<String, Object> queryParam = new HashMap<String, Object>();
		 queryParam.put("organids", cUserOrganIds);
		 queryParam.put("name", name);
		 queryParam.put("phone", phone);
		 queryParam.put("hybh", hybh);
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		 queryParam.put("today", sdf.format(new Date()));
//		 queryParam.put("today", "2017-10-10");
		 List<Record> lis = find(CustomerService.sqlId_selSerTodayByOrganids, queryParam);
		return lis;
	}
	/**今日服务合计功能数据
	 * 
	 * @param cUserOrganIds 机构Ids
	 * @return
	 */
	public Record totaloftodayservice(String cUserOrganIds){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Record record = new Record();
		//到店人数
		String sqloftotalofpeople = "SELECT count(*) AS totalofpeople FROM sb_customer_service AS sbcs WHERE sbcs.organids = ? AND DATE_FORMAT(sbcs.startTime,'%Y-%m-%d')=?";
		//涨秤人数
		String sqloftotalofupweightpeople = "SELECT count(*) AS totalofupweightpeople FROM sb_customer_service AS sbcs WHERE sbcs.organids = ? AND DATE_FORMAT(sbcs.startTime,'%Y-%m-%d')=? AND sbcs.weight-sbcs.lastWeight>0";
		//平秤人数
		String sqloftotalofnoloseweight = "SELECT count(*) AS totalofnoloseweight FROM sb_customer_service AS sbcs WHERE sbcs.organids = ? AND DATE_FORMAT(sbcs.startTime,'%Y-%m-%d')=? AND sbcs.weight-sbcs.lastWeight=0";
		//减秤人数
		String sqloftotalofdownweightpeople = "SELECT count(*) AS totalofdownweightpeople FROM sb_customer_service AS sbcs WHERE sbcs.organids = ? AND DATE_FORMAT(sbcs.startTime,'%Y-%m-%d')=? AND sbcs.weight-sbcs.lastWeight<0";
		//涨秤斤数
		String sqlupweight = "SELECT SUM( sbcs.weight - sbcs.lastWeight ) AS upweight FROM sb_customer_service AS sbcs WHERE sbcs.organids = ? AND DATE_FORMAT(sbcs.startTime, '%Y-%m-%d') = ? AND sbcs.weight - sbcs.lastWeight > 0";
		//掉秤斤数
		String sqldownweight = "SELECT SUM( sbcs.lastWeight - sbcs.weight ) AS downweight FROM sb_customer_service AS sbcs WHERE sbcs.organids = ? AND DATE_FORMAT(sbcs.startTime, '%Y-%m-%d') = ? AND sbcs.weight - sbcs.lastWeight < 0";
		//精护人数
		String sqljinghu = "SELECT count(sbcs.isShaping) AS jinghu FROM sb_customer_service AS sbcs WHERE sbcs.organids = ? AND DATE_FORMAT(sbcs.startTime, '%Y-%m-%d') = ? AND sbcs.isShaping = '1'";
		//巩固人数
		String sqlofgonggu = "SELECT count(*) AS gonggurenshu FROM sb_customer_service AS sbcs WHERE sbcs.organids = ? AND DATE_FORMAT(sbcs.startTime, '%Y-%m-%d') =? AND sbcs.isGg = '1'";
		Record result = Db.findFirst(sqloftotalofpeople,cUserOrganIds,sdf.format(new Date()));
		Record resultupweight = Db.findFirst(sqloftotalofupweightpeople,cUserOrganIds,sdf.format(new Date()));
		Record resultdownweight = Db.findFirst(sqloftotalofdownweightpeople,cUserOrganIds,sdf.format(new Date()));
		Record resultnoloseweight = Db.findFirst(sqloftotalofnoloseweight,cUserOrganIds,sdf.format(new Date()));
		Record upweight = Db.findFirst(sqlupweight,cUserOrganIds,sdf.format(new Date()));
		Record downweight = Db.findFirst(sqldownweight,cUserOrganIds,sdf.format(new Date()));
		Record jinghu = Db.findFirst(sqljinghu,cUserOrganIds,sdf.format(new Date()));
		Record gonggu = Db.findFirst(sqlofgonggu,cUserOrganIds,sdf.format(new Date()));
		record.set("date", sdf.format(new Date()))
			  .set("totalofpeople", result.get("totalofpeople"))
			  .set("totalofupweightpeople",resultupweight.get("totalofupweightpeople"))
			  .set("totalofdownweightpeople", resultdownweight.get("totalofdownweightpeople"))
			  .set("totalofnoloseweight", resultnoloseweight.get("totalofnoloseweight"))
			  .set("upweight", upweight.get("upweight")==null?"0":upweight.get("upweight"))
			  .set("downweight", downweight.get("downweight")==null?"0":downweight.get("downweight"))
			  .set("jinghu", jinghu.get("jinghu"))
			  .set("totalloseweight",(float)Math.round((Float.parseFloat(downweight.get("downweight")==null?"0":downweight.get("downweight").toString())-Float.parseFloat(upweight.get("upweight")==null?"0":upweight.get("upweight").toString()))*10)/10)
//			  .set("proportionforloseweight",(float)Math.round(Float.parseFloat(resultdownweight.get("totalofdownweightpeople").toString())/Float.parseFloat(result.get("totalofpeople").toString())*10000)/100)
//			  .set("proportionforjinghu",(float)Math.round(Float.parseFloat(jinghu.get("jinghu").toString())/Float.parseFloat(result.get("totalofpeople").toString())*10000)/100)
			  .set("gonggurenshu", gonggu.get("gonggurenshu"));
		if(result.get("totalofpeople")=="0"){
			  record.set("proportionforloseweight","0")
			  .set("proportionforjinghu","0");
			
		}else{
			  record.set("proportionforloseweight",(float)Math.round(Float.parseFloat(resultdownweight.get("totalofdownweightpeople").toString())/Float.parseFloat(result.get("totalofpeople").toString())*10000)/100)
			  .set("proportionforjinghu",(float)Math.round(Float.parseFloat(jinghu.get("jinghu").toString())/Float.parseFloat(result.get("totalofpeople").toString())*10000)/100);

		}
		return record;
	}

	public List<Record> getNearStaWeight(String cUserOrganIds) {
		 Map<String, Object> queryParam = new HashMap<String, Object>();
		 queryParam.put("organIds", cUserOrganIds);
		 List<Record> lis = find(CustomerService.sqlId_nearStaWeight, queryParam);
		return lis;
	}
	
	
	@SuppressWarnings("unused")
	public void saveOrUpdateNurse(CustomerServiceNurse csmn, CustomerService cs, CustomerDetail cdet,int count,String cid,int flag) throws ParseException {
		//flag 是1为保存或修改，0是删除
		SimpleDateFormat sdf = new SimpleDateFormat("dd");
		SimpleDateFormat ym = new SimpleDateFormat("yyyy-MM");
		SimpleDateFormat year = new SimpleDateFormat("yyyy");
		SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
		
		//-------------------------------------------
		//String sqlNurse = "select * from sb_customer_service_nurse";
		String sqllast = "select * from sb_customer_service where date_format(startTime, '%Y-%m') = ? and customerID = ?  and dataStatus in ('1','2') ORDER BY startTime DESC  LIMIT 0,1";
		String sqlfirst = "select * from sb_customer_service where date_format(startTime, '%Y-%m') = ? and customerID = ?  and dataStatus in ('1','2') ORDER BY startTime  LIMIT 0,1";
		//List<CustomerServiceNurse> customerServiceNurses = CustomerServiceNurse.dao.find(sqlNurse);
/*		for(int i=0;i<customerServiceNurses.size();i++){
			String cusIds = customerServiceNurses.get(i).getStr(CustomerServiceNurse.column_customerID);
			String ymStr = customerServiceNurses.get(i).getStr(CustomerServiceNurse.column_YearMon);
			//查询本月第一次的服务记录
			CustomerService  customerService = CustomerService.dao.findFirst(sqlfirst,ymStr,cusIds);
			float firstWeight  = 0;
			float lastWeight  = 0;
			if(customerService!=null){
				 firstWeight = customerService.getFloat(CustomerService.column_weight);
			}
			
			
			//查询本月最后一次的服务记录
			CustomerService  customerService2 = CustomerService.dao.findFirst(sqllast,ymStr,cusIds);
			if(customerService2!=null){
				lastWeight = customerService2.getFloat(CustomerService.column_weight);
			}
			
			customerServiceNurses.get(i).set(CustomerServiceNurse.column_gjWeight, firstWeight-lastWeight);
			customerServiceNurses.get(i).update();
		}*/
		
		String ymStr = "";
		if(csmn!=null){
			ymStr=csmn.getStr("YearMon");
			String dd = sdf.format(cs.getDate(CustomerService.column_startTime));
			
			if(flag == 1){
				csmn.set("weight"+dd, cs.getFloat("weight"));
			}else if(flag == 0){
				csmn.set("weight"+dd, 0);
			}
			
			
			Record lis = Db.findFirst(getSqlMy(CustomerService.sqlId_selSerByStratTime) , cs.getDate("startTime"),cs.getStr("customerID"));//月初
			Float weight = 0f;
			if(lis!=null){
				 weight =lis.getFloat("weight");
			}else{
				weight =  cdet.getFloat("firstWeight");
			}
			if(flag == 1){
				csmn.set("weightqk"+dd, weight- cs.getFloat("weight")); 
			}
			
			/*if( weight- cs.getFloat("weight")>0){
				csmn.set("gjWeight", csmn.getFloat("gjWeight")+ (weight- cs.getFloat("weight")));
			}*/
			
			String sql = "select * from sb_customer_service where date_format(startTime, '%Y-%m') = ? and customerID = ? and dataStatus in ('1','2') ORDER BY startTime  LIMIT 0,1";
			
			//查询本月第一次的服务记录
			CustomerService  customerService = CustomerService.dao.findFirst(sql,ymStr,cid);
			float firstWeight  = 0;
			float lastWeight  = 0;
			if(customerService!=null){
				 firstWeight = customerService.getFloat(CustomerService.column_weight);
			}
			String sql2 = "select * from sb_customer_service where date_format(startTime, '%Y-%m') = ? and customerID = ?  and dataStatus in ('1','2') ORDER BY startTime DESC  LIMIT 0,1";
			
			//查询本月最后一次的服务记录
			CustomerService  customerService2 = CustomerService.dao.findFirst(sql2,ymStr,cid);
			if(customerService2!=null){
				lastWeight = customerService2.getFloat(CustomerService.column_weight);
			}
			csmn.set("gjWeight",firstWeight-lastWeight);
			
			sdf.format(cs.getDate(CustomerService.column_startTime));
			if(flag == 1){
				csmn.set("ddCount",Integer.parseInt(csmn.getStr("ddCount"))+count+"");
			}else if(flag == 0){
				csmn.set("ddCount",Integer.parseInt(csmn.getStr("ddCount"))-count+"");
			}
			
			
			
			
			csmn.update();
		}else{
			SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
			
			String str=sdf2.format(cs.getDate(CustomerService.column_startTime));
			ymStr = str.substring(0,7);
			csmn = new  CustomerServiceNurse();
			csmn.set("organids", cdet.get(CustomerDetail.column_organIds));
			csmn.set("customerID", cdet.get(CustomerDetail.column_customerIds));
			csmn.set("customerName", cdet.get(CustomerDetail.column_name));
			String dd = sdf.format(cs.getDate(CustomerService.column_startTime));
			csmn.set("weight"+dd, cs.getFloat("weight"));
			Record lis = Db.findFirst(getSqlMy(CustomerService.sqlId_selSerByStratTime) , ymd.format(cs.getDate(CustomerService.column_startTime))  ,cs.getStr("customerID"));
			Float weight = 0f;
			if(lis!=null){
				 weight =lis.getFloat("weight");
			}else{
				weight =  cdet.getFloat("firstWeight");
			}
			csmn.set("weightqk"+dd, weight- cs.getFloat("weight"));
			String sql = "select * from sb_customer_service where date_format(startTime, '%Y-%m') = ? and customerID = ?  and dataStatus in ('1','2') ORDER BY startTime  LIMIT 0,1";
			//查询本月第一次的服务记录
			CustomerService  customerService = CustomerService.dao.findFirst(sql,ymStr,cid);
			float firstWeight  = 0;
			float lastWeight  = 0;
			if(customerService!=null){
				 firstWeight = customerService.getFloat(CustomerService.column_weight);
			}
			String sql2 = "select * from sb_customer_service where date_format(startTime, '%Y-%m') = ? and customerID = ?  and dataStatus in ('1','2') ORDER BY startTime DESC  LIMIT 0,1";
			
			//查询本月最后一次的服务记录
			CustomerService  customerService2 = CustomerService.dao.findFirst(sql2,ymStr,cid);
			if(customerService2!=null){
				lastWeight = customerService2.getFloat(CustomerService.column_weight);
			}
			csmn.set("gjWeight",firstWeight-lastWeight);
			/*if( weight- cs.getFloat("weight")>0){
				csmn.set("gjWeight", (cs.getFloat("weight")));
			}*/
			
			
			csmn.set("ddCount",1);
			csmn.set("YearMon",ym.format(cs.getDate(CustomerService.column_startTime)));
			csmn.save();
		}
		
	}

	public boolean updateOrsaveSerbl(Customer cus, CustomerServiceNurse csn, String cUserIds, String cUserOrganIds) {
		Calendar calendar=Calendar.getInstance();
		int nowmonth=calendar.get(Calendar.MONTH)+1;
		int nowyear = calendar.get(Calendar.YEAR);
		try {
			boolean flag = true;
			boolean hasdb = false;
			String cid = cus.getStr("ids");
			String ym = csn.getStr("YearMon");
			String year = ym.substring(0, 4);
			String month = ym.substring(5, 7);
			float gjWeight = 0f;
			int ddCount = 0;
			int yi =Integer.parseInt(ym.split("-")[1])-1;
			CustomerDetail cdet = CustomerDetail.dao.findFirst("SELECT * FROM sb_customer_detail WHERE customerIds = ?  and dataStatus in ('1','2')",cid);
			String yy = "";
			if(yi<10){
				yy ="0"+yi;
			}else{
				yy = yi+"";
			}
			
			Record  cs  = Db.findFirst("select weight  from sb_customer_service  where  DATE_FORMAT(startTime,'%Y-%m')=? and  customerID = ?  and dataStatus in ('1','2') ORDER BY   startTime DESC ",ym.split("-")[0]+"-"+yy,cid);
			Float  lastweight = cdet.getFloat(CustomerDetail.column_firstWeight);
			if(cs!=null&&cs.getFloat("weight")!=null){
				lastweight = cs.getFloat("weight");
			}
			String dd = "";
			float monthLastWeight  = 0f;
			for (int i = 1; i < 33; i++) {
				if(i<10){
					dd = "0"+i;
				}else{
					dd = i+"";
				}
				String gxsj = ym+"-"+dd;
				Float  weight =csn.getFloat("weight"+dd);
				if(weight!=null && weight>0){
					monthLastWeight = weight;
				}
				CustomerServiceNurse csmn = CustomerServiceNurse.dao.findFirst(" SELECT * FROM sb_customer_service_nurse WHERE customerID = ? and  YearMon = ?   LIMIT 1", cid,ym);
				csn.set(CustomerServiceNurse.column_gjWeight, gjWeight);
				csn.set(CustomerServiceNurse.column_ddCount, ddCount);
				csn.set(CustomerServiceNurse.column_organids, cUserOrganIds);
				csn.set(CustomerServiceNurse.column_customerID, cid);
				csn.set(CustomerServiceNurse.column_customerName, cus.get(Customer.column_name));
				if(csn.save()&&csmn!=null){
					flag =csmn.delete()&&flag;
				}
				
				CustomerServiceMonthNurse monthNurse = CustomerServiceMonthNurse.dao.findFirst("select * from sb_customer_service_month_nurse where customerIds = ? and organIds = ? and `year` = ? and dataStatus in ('1','2')",cid,cUserOrganIds,year);
				if(monthNurse!=null){
					monthNurse.set("lastweight"+month, monthLastWeight)
					.set("ddcount"+month,ddCount)
					.set(CustomerServiceMonthNurse.column_updateDate, new Date())
					.set(CustomerServiceMonthNurse.column_updateId, cUserIds);
					monthNurse.update();
				}else{
					monthNurse = new CustomerServiceMonthNurse();
					monthNurse.set("organIds", cUserOrganIds)
					.set("customerIds",cid)
					.set("customerName", cdet.get(CustomerDetail.column_name))
					.set("lastweight"+month, monthLastWeight)
					.set(CustomerServiceMonthNurse.column_createDate, new Date())
					.set(CustomerServiceMonthNurse.column_createId, cUserIds)
					.set(CustomerServiceMonthNurse.column_dataStatus,"2")
					.set("ddcount"+month,ddCount)
					.set("year",year);
					monthNurse.save();
				}
				
				String  bz =csn.getStr("weightqk"+dd);
				Float standardWeight = Float.parseFloat(cdet.getStr(CustomerDetail.column_standardWeight));
				if(weight!=null&&weight>0){
					
					CustomerService cd = CustomerService.dao.findFirst("select *  from sb_customer_service  where  DATE_FORMAT(startTime, '%Y-%m-%d')=? and  customerID = ? and dataStatus in ('1','2')",gxsj,cid);
					if(cd!=null){
						
						String  ssql = "SELECT * FROM sb_customer_service  WHERE  organids = ? AND  customerID = ? AND  startTime < ? ORDER BY  startTime DESC LIMIT 0,1";//补录日期前一次服务
						String xsql = "SELECT * FROM sb_customer_service  WHERE  organids = ? AND  customerID = ? AND  startTime > ? ORDER BY  startTime LIMIT 0,1";//补录日期后一次服务
						CustomerService  scs = CustomerService.dao.findFirst(ssql,cd.getStr(CustomerService.column_organids),cid,ToolDateTime.format(cd.getDate(CustomerService.column_startTime), ToolDateTime.pattern_ymd));
						CustomerService  xcs = CustomerService.dao.findFirst(xsql,cd.getStr(CustomerService.column_organids),cid,ToolDateTime.format(cd.getDate(CustomerService.column_startTime), ToolDateTime.pattern_ymd));
						
						//更新日护理综合查询表
						DailyNursingTotal  dnt = DailyNursingTotal.dao.getDnt(cUserOrganIds, sdf.parse(gxsj));
						if(dnt != null)
						{	
							if(scs!=null)
							{	
								float js = weight - scs.getFloat(CustomerService.column_weight);//修改之后
								float cjs = cd.getFloat(CustomerService.column_weight) - scs.getFloat(CustomerService.column_weight);//修改之前
								if(js>0  &&  cjs<0 )//修改后为涨称，修改之前为掉秤
								{
									dnt.set(DailyNursingTotal.column_dcrs, dnt.getInt(DailyNursingTotal.column_dcrs) - 1)
										.set(DailyNursingTotal.column_dcjs, dnt.getDouble(DailyNursingTotal.column_dcjs) - (-cjs))
										.set(DailyNursingTotal.column_zcrs, dnt.getInt(DailyNursingTotal.column_zcrs)+1)
										.set(DailyNursingTotal.column_zcjs, dnt.getDouble(DailyNursingTotal.column_zcjs) + js);
									double  dcbl = ((double)dnt.getInt(DailyNursingTotal.column_dcrs))/((double)dnt.getInt(DailyNursingTotal.column_sddrs));
									dnt.set(DailyNursingTotal.column_dcrszb,new DecimalFormat("#.00").format(dcbl*100));
									if(!dnt.update())
									{
										log.debug("更新日综合查询表达标人数失败！！");
										throw new RuntimeException("更新日综合查询表达标人数失败!");
									}
								}
								if(js<0 &&  cjs<0 )//修改后为掉秤，修改前为涨称
								{
									dnt.set(DailyNursingTotal.column_dcrs, dnt.getInt(DailyNursingTotal.column_dcrs) + 1)
									.set(DailyNursingTotal.column_dcjs, dnt.getDouble(DailyNursingTotal.column_dcjs) + (-cjs))
									.set(DailyNursingTotal.column_zcrs, dnt.getInt(DailyNursingTotal.column_zcrs) - 1)
									.set(DailyNursingTotal.column_zcjs, dnt.getDouble(DailyNursingTotal.column_zcjs) - js);
									double  dcbl = ((double)dnt.getInt(DailyNursingTotal.column_dcrs))/((double)dnt.getInt(DailyNursingTotal.column_sddrs));
									dnt.set(DailyNursingTotal.column_dcrszb,new DecimalFormat("#.00").format(dcbl*100));
									if(!dnt.update())
									{
										log.debug("更新日综合查询表达标人数失败！！");
										throw new RuntimeException("更新日综合查询表达标人数失败!");
									}
								}
							}
							if(xcs != null)
							{	
								float xjs = xcs.getFloat(CustomerService.column_weight) - weight;
								float cjs = xcs.getFloat(CustomerService.column_weight) - cd.getFloat(CustomerService.column_weight);
								DailyNursingTotal  xdnt = DailyNursingTotal.dao.getDnt(cUserOrganIds,xcs.getDate(CustomerService.column_startTime));//补录服务的下一次服务
								if(xdnt != null)
								{
									if(xjs > 0 && cjs <0)//修改后为涨称，修改前为掉秤
									{
										xdnt.set(DailyNursingTotal.column_dcrs, xdnt.getInt(DailyNursingTotal.column_dcrs) - 1)
											.set(DailyNursingTotal.column_dcjs, xdnt.getFloat(DailyNursingTotal.column_dcjs)- (-cjs))
											.set(DailyNursingTotal.column_zcrs, xdnt.getInt(DailyNursingTotal.column_zcrs) + 1)
											.set(DailyNursingTotal.column_zcjs, xdnt.getInt(DailyNursingTotal.column_zcjs) + xjs);
										double  dcbl = ((double)xdnt.getInt(DailyNursingTotal.column_dcrs))/((double)xdnt.getInt(DailyNursingTotal.column_sddrs));
										xdnt.set(DailyNursingTotal.column_dcrszb,new DecimalFormat("#.00").format(dcbl*100));
										if (!xdnt.update()) {
											log.debug("更新日综合查询表失败");
											throw new RuntimeException("更新日综合查询表失败!");
										}
									}
									if(xjs < 0 && cjs > 0)//修改后为掉秤，修改前为涨称
									{
										xdnt.set(DailyNursingTotal.column_dcrs, xdnt.getInt(DailyNursingTotal.column_dcrs) + 1)
										.set(DailyNursingTotal.column_dcjs, xdnt.getFloat(DailyNursingTotal.column_dcjs) + (-xjs))
										.set(DailyNursingTotal.column_zcrs, xdnt.getInt(DailyNursingTotal.column_zcrs) - 1)
										.set(DailyNursingTotal.column_zcjs, xdnt.getInt(DailyNursingTotal.column_zcjs) - cjs);
										double  dcbl = ((double)xdnt.getInt(DailyNursingTotal.column_dcrs))/((double)xdnt.getInt(DailyNursingTotal.column_sddrs));
										xdnt.set(DailyNursingTotal.column_dcrszb,new DecimalFormat("#.00").format(dcbl*100));
										if (!xdnt.update()) {
											log.debug("更新日综合查询表失败");
											throw new RuntimeException("更新日综合查询表失败!");
										}
									}
								}	
							}
							
							if(cd.getFloat(CustomerService.column_weight) < standardWeight  && weight > standardWeight)//当时录入为达标，补录修改体重为不达标的情况
							{
								dnt.set(DailyNursingTotal.column_dbrs, dnt.getInt(DailyNursingTotal.column_dbrs)-1);
								if(!dnt.update())
								{
									log.debug("更新日综合查询表达标人数失败！！");
									throw new RuntimeException("更新日综合查询表达标人数失败!");
								}
							}
							if(cd.getFloat(CustomerService.column_weight) > standardWeight  && weight < standardWeight)//当时录入为不达标，补录修改体重为达标的情况
							{
								dnt.set(DailyNursingTotal.column_dbrs, dnt.getInt(DailyNursingTotal.column_dbrs)+1);
								if(!dnt.update())
								{
									log.debug("更新日综合查询表达标人数失败！！");
									throw new RuntimeException("更新日综合查询表达标人数失败!");
								}
							}
							
						}
						//更新月综合查询表
						MonthTotal mt = MonthTotal.dao.getMonthTotal(cUserOrganIds, sdf.parse(gxsj));
						if(mt != null)
						{
							if(cd.getFloat(CustomerService.column_weight) < standardWeight  && weight > standardWeight)//当时录入为达标，补录修改体重为不达标的情况
							{
								mt.set(MonthTotal.column_dbrs, mt.getInt(MonthTotal.column_dbrs)-1);
								if(!mt.update())
								{
									log.debug("更新月综合查询表达标人数失败！！");
									throw new RuntimeException("更新月综合查询表达标人数失败!");
								}
							}
							if(cd.getFloat(CustomerService.column_weight) > standardWeight  && weight < standardWeight)//当时录入为不达标，补录修改体重为达标的情况
							{	
								
								mt.set(MonthTotal.column_dbrs, mt.getInt(MonthTotal.column_dbrs)+1);
								if(!mt.update())
								{
									log.debug("更新月综合查询表达标人数失败！！");
									throw new RuntimeException("更新月综合查询表达标人数失败!");
								}
							}
							
						}
						//更新年综合查询表
						YearTotal yt = YearTotal.dao.getYearTotal(cUserOrganIds, sdf.parse(gxsj));
						if(yt != null)
						{
							if(cd.getFloat(CustomerService.column_weight) < standardWeight  && weight > standardWeight)//当时录入为达标，补录修改体重为不达标的情况
							{
								yt.set(YearTotal.column_dbrs, yt.getInt(YearTotal.column_dbrs)-1);
								if(!yt.update())
								{
									log.debug("更新年综合查询表达标人数失败！！");
									throw new RuntimeException("更新年综合查询表达标人数失败!");
								}
							}
							if(cd.getFloat(CustomerService.column_weight) > standardWeight  && weight < standardWeight)//当时录入为不达标，补录修改体重为达标的情况
							{	
								
								yt.set(YearTotal.column_dbrs, yt.getInt(YearTotal.column_dbrs)+1);
								if(!yt.update())
								{
									log.debug("更新年综合查询表达标人数失败！！");
									throw new RuntimeException("更新年综合查询表达标人数失败!");
								}
							}
							
						}
						if(null != cd.getStr(CustomerService.column_isGg)  && cd.getStr(CustomerService.column_isGg).equals("0"))
						{
							hasdb = true;
						}
						cd.set(CustomerService.column_weight, weight)
						  .set(CustomerService.column_lastWeight, lastweight)
						  .set(CustomerService.column_bz, bz)
						  //.set(CustomerService.column_dataStatus, 2)
						  .set(CustomerService.column_updateId, cUserIds)
						  .set(CustomerService.column_updateDate, new Date())
						  .set(CustomerService.column_isGg, 0);
							flag = cd.update()&&flag;
					}else{
						  	cd = new CustomerService();
						  	cd.set(CustomerService.column_weight, weight)
						   .set(CustomerService.column_organids, cUserOrganIds)
						   .set(CustomerService.column_customerID, cid)
						   .set(CustomerService.column_startTime, gxsj)
						   .set(CustomerService.column_endTime, gxsj)
						   .set(CustomerService.column_lastWeight, lastweight)
						   .set(CustomerService.column_bz, bz)
						   .set(CustomerService.column_dataStatus, 2)
						   .set(CustomerService.column_createId, cUserIds)
						   .set(CustomerService.column_createDate, new Date())
						  	.set(CustomerService.column_isGg, 0);
						  	flag =cd.save()&&flag;
						  	
						  	//保存日护理综合查询
						  	DailyNursingTotal  dnt = DailyNursingTotal.dao.getDnt(cUserOrganIds, sdf.parse(gxsj));
							if(dnt != null)
							{
								dnt.set(DailyNursingTotal.column_sddrs, dnt.getInt(DailyNursingTotal.column_sddrs)+1)
								.set(DailyNursingTotal.column_fwrs, dnt.getInt(DailyNursingTotal.column_fwrs)+1)
								.set(DailyNursingTotal.column_fwcs, dnt.getInt(DailyNursingTotal.column_fwcs)+1);
								if(weight < standardWeight)
								{
									dnt.set(DailyNursingTotal.column_dbrs, dnt.getInt(DailyNursingTotal.column_dbrs)+1);
								}
								if (!dnt.update()) {
									log.debug("更新日护理综合查询表失败");
									throw new RuntimeException("更新日护理综合查询表失败!");
								}
							}else
							{
								DailyNursingTotal  dntNew = new DailyNursingTotal();
								dntNew.set(DailyNursingTotal.column_organids, cUserOrganIds)
									  .set(DailyNursingTotal.column_date, ToolDateTime.format(sdf.parse(gxsj), ToolDateTime.pattern_ymd))
									  .set(DailyNursingTotal.column_sddrs, 1)
									  .set(DailyNursingTotal.column_fwrs, 1)
									  .set(DailyNursingTotal.column_fwcs, 1);
								if(weight < standardWeight)
								{
									dntNew.set(DailyNursingTotal.column_dbrs,1);
								}
								if (!dntNew.save()) {
									log.debug("保存日护理综合查询表失败");
									throw new RuntimeException("保存日护理综合查询表失败!");
								}
							}
							//保存月综合查询
						  	MonthTotal  mt = MonthTotal.dao.getMonthTotal(cUserOrganIds, sdf.parse(gxsj));
						  	List<CustomerService> csList = CustomerService.dao.getCusSerByMonth(cUserOrganIds, cUserIds, ToolDateTime.format(sdf.parse(gxsj), ToolDateTime.pattern_ym));
							if(mt != null)
							{	
								if(csList == null)
								{
									mt.set(MonthTotal.column_sddrs, mt.getInt(MonthTotal.column_sddrs)+1)
									.set(MonthTotal.column_fwrs, mt.getInt(MonthTotal.column_fwrs)+1);
								}
								mt.set(MonthTotal.column_fwcs, mt.getInt(MonthTotal.column_fwcs)+1);
								if(weight < standardWeight && hasdb)
								{
									mt.set(MonthTotal.column_dbrs, mt.getInt(MonthTotal.column_dbrs)+1);
								}
								if (!mt.update()) {
									log.debug("更新月综合查询表失败");
									throw new RuntimeException("更新月综合查询表失败!");
								}
							}else
							{
								MonthTotal  dntNew = new MonthTotal();
								dntNew.set(MonthTotal.column_organids, cUserOrganIds)
									  .set(MonthTotal.column_date, ToolDateTime.format(sdf.parse(gxsj), ToolDateTime.pattern_ym))
									  .set(MonthTotal.column_sddrs, 1)
									  .set(MonthTotal.column_fwrs, 1)
									  .set(MonthTotal.column_fwcs, 1);
								if(weight < standardWeight)
								{
									dntNew.set(MonthTotal.column_dbrs,1);
								}
								if (!dntNew.save()) {
									log.debug("保存月综合查询表失败");
									throw new RuntimeException("保存月综合查询表失败!");
								}
							}
							//保存年综合查询
						  	YearTotal  yt = YearTotal.dao.getYearTotal(cUserOrganIds, sdf.parse(gxsj));
						  	List<CustomerService> yearcsList = CustomerService.dao.getCusSerByMonth(cUserOrganIds, cUserIds, ToolDateTime.format(sdf.parse(gxsj), ToolDateTime.pattern_y));
							if(yt != null)
							{	
								if(yearcsList == null)
								{
									yt.set(YearTotal.column_sddrs, yt.getInt(YearTotal.column_sddrs)+1)
									.set(YearTotal.column_fwrs, yt.getInt(YearTotal.column_fwrs)+1);
								}
								yt.set(YearTotal.column_fwcs, yt.getInt(YearTotal.column_fwcs)+1);
								if(weight < standardWeight && hasdb)
								{
									yt.set(YearTotal.column_dbrs, yt.getInt(YearTotal.column_dbrs)+1);
								}
								int ssyear= Integer.parseInt(sdf.format(gxsj).substring(0, 4));
								if(ssyear != nowyear)
								{
									nowmonth = 12;
								}
								yt.set(YearTotal.column_yjfwrs, yt.getInt(YearTotal.column_fwrs)/nowmonth)
									.set(YearTotal.column_yjfwcs, yt.getInt(YearTotal.column_fwcs)/nowmonth)
									.set(YearTotal.column_yjdbrs, yt.getInt(YearTotal.column_dbrs)/nowmonth);
								if (!yt.update()) {
									log.debug("更新年综合查询表失败");
									throw new RuntimeException("更新年综合查询表失败!");
								}
							}else
							{
								YearTotal  ytNew = new YearTotal();
								ytNew.set(YearTotal.column_organids, cUserOrganIds)
									  .set(YearTotal.column_date, ToolDateTime.format(sdf.parse(gxsj), ToolDateTime.pattern_y))
									  .set(YearTotal.column_sddrs, 1)
									  .set(YearTotal.column_fwrs, 1)
									  .set(YearTotal.column_fwcs, 1);
								if(weight < standardWeight)
								{
									ytNew.set(YearTotal.column_dbrs,1);
								}
								if (!ytNew.save()) {
									log.debug("保存年综合查询表失败");
									throw new RuntimeException("保存年综合查询表失败!");
								}
							}
						
					}
				
					String customerType = cdet.getStr(CustomerDetail.column_customerType);
					if(StringUtils.isNotBlank(customerType)&&customerType.equals("2")){
						 cd.set(CustomerService.column_isGg, 1+"");
						 flag =cd.update()&&flag;
					}
					if(StringUtils.isNotBlank(customerType)&&customerType.equals("1")){
						 cd.set(CustomerService.column_isGg, 2+"");
						 flag =cd.update()&&flag;
					}
					
					if(weight<=standardWeight){
						 cd.set(CustomerService.column_isGg, 1+"");
						 cdet.set(CustomerDetail.column_customerType,2+"");
						 flag =cd.update()&&flag;
						 flag =cdet.update()&&flag;
					}
					
					
					String servicesql = getSqlMy(CustomerService.sqlId_selNextWeight);
					CustomerService cs0 = CustomerService.dao.findFirst(servicesql ,gxsj,cid);
					if (cs0 != null) {
						cs0.set(CustomerService.column_lastWeight, weight);
						cs0.set(CustomerService.column_updateDate, new Date());
						cs0.set(CustomerService.column_updateId, cUserIds);
						flag =cs0.update()&&flag;
					}
					csn.set("weightqk"+dd,lastweight-weight);
					String sql = "select * from sb_customer_service where date_format(startTime, '%Y-%m') = ? and customerID = ?  and dataStatus in ('1','2') ORDER BY startTime  LIMIT 0,1";
					
					//查询本月第一次的服务记录
					CustomerService  customerService = CustomerService.dao.findFirst(sql,ym,cid);
					if(customerService!=null){
						
						float firstWeight = customerService.getFloat(CustomerService.column_weight);
						gjWeight =firstWeight-(weight);
					}else{
						gjWeight =0;
					}
					//gjWeight += (lastweight-weight);
					ddCount +=1;
					lastweight = weight;
				}
			}
			
			
			String servicesql = getSqlMy(CustomerService.sqlId_selMinByCus);
			CustomerService cs1 = CustomerService.dao.findFirst(servicesql, cid);
			if (cs1 != null) {
				cdet.set(CustomerDetail.column_minDate, cs1.getDate(CustomerService.column_startTime));
				cdet.set(CustomerDetail.column_minWeight, cs1.getFloat(CustomerService.column_weight));
				cdet.set(CustomerDetail.column_updateDate, new Date());
				cdet.set(CustomerDetail.column_updateId, cUserIds);
				flag =cdet.update()&&flag;
			}
			
			
			servicesql = getSqlMy(CustomerService.sqlId_selNowByCus);
			CustomerService cs2 = CustomerService.dao.findFirst(servicesql, cid);
			if (cs2 != null) {
				cdet.set(CustomerDetail.column_toStoreDate, cs2.getDate(CustomerService.column_startTime));
				cdet.set(CustomerDetail.column_nowWeight, cs2.getFloat(CustomerService.column_weight));
				cdet.set(CustomerDetail.column_updateDate, new Date());
				cdet.set(CustomerDetail.column_updateId, cUserIds);
				flag = cdet.update()&&flag;
			}
			
			
			
			
			return flag;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
		
	}
	
	
	
	public  void  saveTotal(String organids,Date date,boolean isdb,String cid,float weight)
	{	
		//掉秤人数
		String  ssql = "SELECT * FROM sb_customer_service  WHERE  organids = ? AND  customerID = ? AND  startTime < ? ORDER BY  startTime DESC LIMIT 0,1";//补录日期前一次服务
		String xsql = "SELECT * FROM sb_customer_service  WHERE  organids = ? AND  customerID = ? AND  startTime > ? ORDER BY  startTime LIMIT 0,1";//补录日期后一次服务
		CustomerService  scs = CustomerService.dao.findFirst(ssql,organids,cid,ToolDateTime.format(date, ToolDateTime.pattern_ymd));
		CustomerService  xcs = CustomerService.dao.findFirst(xsql,organids,cid,ToolDateTime.format(date, ToolDateTime.pattern_ymd));
		

		//保存日综合查询（实到店人数，服务人数，服务次数，达标人数）
		DailyNursingTotal  dnt = DailyNursingTotal.dao.getDnt(organids,date);
		if(dnt != null)
		{
			dnt.set(DailyNursingTotal.column_sddrs, dnt.getInt(DailyNursingTotal.column_sddrs)+1)
				.set(DailyNursingTotal.column_fwrs, dnt.getInt(DailyNursingTotal.column_fwrs)+1)
				.set(DailyNursingTotal.column_fwcs, dnt.getInt(DailyNursingTotal.column_fwcs)+1);
			if(isdb)
			{
				dnt.set(DailyNursingTotal.column_dbrs, dnt.getInt(DailyNursingTotal.column_dbrs)+1);
			}
			if(scs!=null)
			{	
				float js = weight - scs.getFloat(CustomerService.column_weight);
				if(js>0)
				{
					dnt.set(DailyNursingTotal.column_zcrs, dnt.getInt(DailyNursingTotal.column_zcrs)+1)//涨称人数
						.set(DailyNursingTotal.column_zcjs, dnt.getDouble(DailyNursingTotal.column_zcjs)+js);
				}
				if(js<0)
				{
					dnt.set(DailyNursingTotal.column_dcrs, dnt.getInt(DailyNursingTotal.column_dcrs)+1)//掉称人数
						.set(DailyNursingTotal.column_dcjs, dnt.getDouble(DailyNursingTotal.column_dcjs)+(-js));
				}
				if(js==0)
				{
					dnt.set(DailyNursingTotal.column_pcrs, dnt.getInt(DailyNursingTotal.column_pcrs)+1);//平称人数
				}
				double  dcbl = ((double)dnt.getInt(DailyNursingTotal.column_dcrs))/((double)dnt.getInt(DailyNursingTotal.column_sddrs));
				dnt.set(DailyNursingTotal.column_dcrszb,new DecimalFormat("#.00").format(dcbl*100));
			}
			if(xcs != null)
			{	
				float xjs = xcs.getFloat(CustomerService.column_weight) - weight;
				float sjs = 0f;
				if(scs !=null)
				{
					sjs = xcs.getFloat(CustomerService.column_weight) - scs.getFloat(CustomerService.column_weight);
				}
				DailyNursingTotal  xdnt = DailyNursingTotal.dao.getDnt(organids,xcs.getDate(CustomerService.column_startTime));//补录服务的下一次服务
				if(xdnt != null)
				{
					if(xjs > 0 && sjs <0)//补录为涨称,旧记录为掉秤，
					{
						xdnt.set(DailyNursingTotal.column_dcrs, xdnt.getInt(DailyNursingTotal.column_dcrs) - 1)
							.set(DailyNursingTotal.column_dcjs, xdnt.getFloat(DailyNursingTotal.column_dcjs)- (-sjs))
							.set(DailyNursingTotal.column_zcrs, xdnt.getInt(DailyNursingTotal.column_zcrs) + 1)
							.set(DailyNursingTotal.column_zcjs, xdnt.getInt(DailyNursingTotal.column_zcjs) + xjs);
						double  dcbl = ((double)xdnt.getInt(DailyNursingTotal.column_dcrs))/((double)xdnt.getInt(DailyNursingTotal.column_sddrs));
						xdnt.set(DailyNursingTotal.column_dcrszb,new DecimalFormat("#.00").format(dcbl*100));
						if (!xdnt.update()) {
							log.debug("更新日综合查询表失败");
							throw new RuntimeException("更新日综合查询表失败!");
						}
					}
					if(xjs < 0 && sjs > 0)//补录为掉称,旧记录为涨秤，
					{
						xdnt.set(DailyNursingTotal.column_dcrs, xdnt.getInt(DailyNursingTotal.column_dcrs) + 1)
						.set(DailyNursingTotal.column_dcjs, xdnt.getFloat(DailyNursingTotal.column_dcjs) + (-xjs))
						.set(DailyNursingTotal.column_zcrs, xdnt.getInt(DailyNursingTotal.column_zcrs) - 1)
						.set(DailyNursingTotal.column_zcjs, xdnt.getInt(DailyNursingTotal.column_zcjs) - sjs);
						double  dcbl = ((double)xdnt.getInt(DailyNursingTotal.column_dcrs))/((double)xdnt.getInt(DailyNursingTotal.column_sddrs));
						xdnt.set(DailyNursingTotal.column_dcrszb,new DecimalFormat("#.00").format(dcbl*100));
						if (!xdnt.update()) {
							log.debug("更新日综合查询表失败");
							throw new RuntimeException("更新日综合查询表失败!");
						}
					}
				}	
			}
			if (!dnt.update()) {
				log.debug("更新日综合查询表失败");
				throw new RuntimeException("更新日综合查询表失败!");
			}
		}else
		{
			DailyNursingTotal  dntNew = new DailyNursingTotal();
			dntNew.set(DailyNursingTotal.column_organids, organids)
				  .set(DailyNursingTotal.column_date, ToolDateTime.format(date, ToolDateTime.pattern_ymd))
				  .set(DailyNursingTotal.column_sddrs, 1)
				  .set(DailyNursingTotal.column_fwrs, 1)
				  .set(DailyNursingTotal.column_fwcs, 1);
			if(isdb)
			{
				dntNew.set(DailyNursingTotal.column_dbrs,1);
			}
			if(scs!=null)
			{	
				double  dcbl =  0.0;
				float js = weight - scs.getFloat(CustomerService.column_weight);
				if(js>0)
				{
					dntNew.set(DailyNursingTotal.column_zcrs,1)//涨称人数
						.set(DailyNursingTotal.column_zcjs,js);
				}
				if(js<0)
				{
					dntNew.set(DailyNursingTotal.column_dcrs, 1)//掉称人数
						.set(DailyNursingTotal.column_dcjs,(-js));
					dcbl = ((double)dntNew.getInt(DailyNursingTotal.column_dcrs))/((double)dntNew.getInt(DailyNursingTotal.column_sddrs));
					
				}
				if(js==0)
				{
					dntNew.set(DailyNursingTotal.column_pcrs,1);//平称人数
				}
				dntNew.set(DailyNursingTotal.column_dcrszb,new DecimalFormat("#.00").format(dcbl*100));
			}
			if(xcs != null)
			{	
				float xjs = xcs.getFloat(CustomerService.column_weight) - weight;
				float sjs = 0f;
				if(scs !=null)
				{
					sjs = xcs.getFloat(CustomerService.column_weight) - scs.getFloat(CustomerService.column_weight);
				}
				DailyNursingTotal  xdnt = DailyNursingTotal.dao.getDnt(organids,xcs.getDate(CustomerService.column_startTime));//补录服务的下一次服务
				if(xdnt != null)
				{
					if(xjs > 0 && sjs <0)//补录为涨称,旧记录为掉秤，
					{
						xdnt.set(DailyNursingTotal.column_dcrs, xdnt.getInt(DailyNursingTotal.column_dcrs) - 1)
							.set(DailyNursingTotal.column_dcjs, xdnt.getFloat(DailyNursingTotal.column_dcjs)- (-sjs))
							.set(DailyNursingTotal.column_zcrs, xdnt.getInt(DailyNursingTotal.column_zcrs) + 1)
							.set(DailyNursingTotal.column_zcjs, xdnt.getInt(DailyNursingTotal.column_zcjs) + xjs);
						double  dcbl = ((double)xdnt.getInt(DailyNursingTotal.column_dcrs))/((double)xdnt.getInt(DailyNursingTotal.column_sddrs));
						xdnt.set(DailyNursingTotal.column_dcrszb,new DecimalFormat("#.00").format(dcbl*100));
						if (!xdnt.update()) {
							log.debug("更新日综合查询表失败");
							throw new RuntimeException("更新日综合查询表失败!");
						}
					}
					if(xjs < 0 && sjs > 0)//补录为掉称,旧记录为涨秤，
					{
						xdnt.set(DailyNursingTotal.column_dcrs, xdnt.getInt(DailyNursingTotal.column_dcrs) + 1)
						.set(DailyNursingTotal.column_dcjs, xdnt.getFloat(DailyNursingTotal.column_dcjs) + (-xjs))
						.set(DailyNursingTotal.column_zcrs, xdnt.getInt(DailyNursingTotal.column_zcrs) - 1)
						.set(DailyNursingTotal.column_zcjs, xdnt.getInt(DailyNursingTotal.column_zcjs) - sjs);
						double  dcbl = ((double)xdnt.getInt(DailyNursingTotal.column_dcrs))/((double)xdnt.getInt(DailyNursingTotal.column_sddrs));
						xdnt.set(DailyNursingTotal.column_dcrszb,new DecimalFormat("#.00").format(dcbl*100));
						if (!xdnt.update()) {
							log.debug("更新日综合查询表失败");
							throw new RuntimeException("更新日综合查询表失败!");
						}
					}
				}	
			}
			if (!dntNew.save()) {
				log.debug("保存日综合查询表失败");
				throw new RuntimeException("保存日综合查询表失败!");
			}
		}
		//保存月综合查询（实到店人数，服务人数，服务次数，达标人数）
		MonthTotal  mt = MonthTotal.dao.getMonthTotal(organids,date);
		String  mdsql = "SELECT  COUNT(ids) dcrs,SUM(gjWeight) dcjs from  sb_customer_service_nurse  WHERE  organids = ?  AND  YearMon = ?  AND gjWeight <0";
		Record  cdsn =  Db.findFirst(mdsql,organids,ToolDateTime.format(date, ToolDateTime.pattern_ym));
		String  mzsql = "SELECT  COUNT(ids) zcrs,SUM(gjWeight) zcjs from  sb_customer_service_nurse  WHERE  organids = ?  AND  YearMon = ?  AND gjWeight >0";
		Record  czsn =  Db.findFirst(mzsql,organids,ToolDateTime.format(date, ToolDateTime.pattern_ym));
		String  mpsql = "SELECT  COUNT(ids) pcrs from  sb_customer_service_nurse  WHERE  organids = ?  AND  YearMon = ?  AND gjWeight =0";
		Record  cpsn =  Db.findFirst(mpsql,organids,ToolDateTime.format(date, ToolDateTime.pattern_ym));
		if(mt != null)
		{
			mt.set(MonthTotal.column_sddrs, mt.getInt(MonthTotal.column_sddrs)+1)
				.set(MonthTotal.column_fwrs, mt.getInt(MonthTotal.column_fwrs)+1)
				.set(MonthTotal.column_fwcs, mt.getInt(MonthTotal.column_fwcs)+1);
			if(isdb)
			{
				mt.set(MonthTotal.column_dbrs, mt.getInt(MonthTotal.column_dbrs)+1);
			}
			if(cdsn != null)
			{
				mt.set(MonthTotal.column_dcrs,Integer.parseInt(cdsn.getLong("dcrs")+""))
				.set(MonthTotal.column_dcjs, -cdsn.getDouble("dcjs"));
			}
			if(czsn != null)
			{
				mt.set(MonthTotal.column_zcrs,Integer.parseInt(czsn.getLong("zcrs")+""))
				.set(MonthTotal.column_zcjs, czsn.getDouble("zcjs"));
			}
			if(cpsn != null)
			{
				mt.set(MonthTotal.column_pcrs,Integer.parseInt(cpsn.getLong("pcrs")+""));
			}
			double  dcbl = ((double)mt.getInt(DailyNursingTotal.column_dcrs))/((double)mt.getInt(DailyNursingTotal.column_sddrs));
			mt.set(DailyNursingTotal.column_dcrszb,new DecimalFormat("#.00").format(dcbl*100));
			if (!mt.update()) {
				log.debug("更新月综合查询表失败");
				throw new RuntimeException("更新月综合查询表失败!");
			}
		}else
		{
			MonthTotal  dntNew = new MonthTotal();
			dntNew.set(MonthTotal.column_organids, organids)
				  .set(MonthTotal.column_date, ToolDateTime.format(date, ToolDateTime.pattern_ym))
				  .set(MonthTotal.column_sddrs, 1)
				  .set(MonthTotal.column_fwrs, 1)
				  .set(MonthTotal.column_fwcs, 1);
			if(isdb)
			{
				dntNew.set(MonthTotal.column_dbrs,1);
			} 
			if(cdsn != null)
			{
				dntNew.set(MonthTotal.column_dcrs,Integer.parseInt(cdsn.getLong("dcrs")+""))
				.set(MonthTotal.column_dcjs, -cdsn.getDouble("dcjs"));
			}
			if(czsn != null)
			{
				dntNew.set(MonthTotal.column_zcrs,Integer.parseInt(czsn.getLong("zcrs")+""))
				.set(MonthTotal.column_zcjs, czsn.getDouble("zcjs"));
			}
			if(cpsn != null)
			{
				dntNew.set(MonthTotal.column_pcrs,Integer.parseInt(cpsn.getLong("pcrs")+""));
			}
			double  dcbl = ((double)dntNew.getInt(DailyNursingTotal.column_dcrs))/((double)dntNew.getInt(DailyNursingTotal.column_sddrs));
			dntNew.set(DailyNursingTotal.column_dcrszb,new DecimalFormat("#.00").format(dcbl*100));
			if (!dntNew.save()) {
				log.debug("保存月综合查询表失败");
				throw new RuntimeException("保存月综合查询表失败!");
			}
		}
		//保存年综合查询（实到店人数，服务人数，服务次数，达标人数）
		YearTotal  yeart = YearTotal.dao.getYearTotal(organids,date);
		if(yeart != null)
		{
			yeart.set(YearTotal.column_sddrs, yeart.getInt(YearTotal.column_sddrs)+1)
				.set(YearTotal.column_fwrs, yeart.getInt(YearTotal.column_fwrs)+1)
				.set(YearTotal.column_fwcs, yeart.getInt(YearTotal.column_fwcs)+1);
			if(isdb)
			{
				yeart.set(YearTotal.column_dbrs, yeart.getInt(YearTotal.column_dbrs)+1);
			}
			Calendar calendar=Calendar.getInstance();
			int month=calendar.get(Calendar.MONTH)+1;
			int year = calendar.get(Calendar.YEAR);
			int ssyear= Integer.parseInt(ToolDateTime.format(date, ToolDateTime.pattern_y));
			if(ssyear != year)
			{
				month = 12;
			}
			yeart.set(YearTotal.column_yjfwrs, yeart.getInt(YearTotal.column_fwrs)/month)
			.set(YearTotal.column_yjfwcs, yeart.getInt(YearTotal.column_fwcs)/month)
			.set(YearTotal.column_yjdbrs, yeart.getInt(YearTotal.column_dbrs)/month);
			if (!yeart.update()) {
				log.debug("更新年综合查询表失败");
				throw new RuntimeException("更新年综合查询表失败!");
			}
		}else
		{
			YearTotal  yeartNew = new YearTotal();
			yeartNew.set(YearTotal.column_organids, organids)
				  .set(YearTotal.column_date, ToolDateTime.format(date, ToolDateTime.pattern_y))
				  .set(YearTotal.column_sddrs, 1)
				  .set(YearTotal.column_fwrs, 1)
				  .set(YearTotal.column_fwcs, 1);
			if(isdb)
			{
				yeartNew.set(YearTotal.column_dbrs,1);
			}
			if (!yeartNew.save()) {
				log.debug("保存年综合查询表失败");
				throw new RuntimeException("保存年综合查询表失败!");
			}
		}
	}
	
}
